﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Text.RegularExpressions;

namespace pnh
{
    class AddGame
    {
        public delegate void consoleWriteLineDelegate(string str);

        private consoleWriteLineDelegate _delConsole;
        private pnhBrowserControl.pnhBowserControl _browser;

        public AddGame(consoleWriteLineDelegate del, pnhBrowserControl.pnhBowserControl b)
        {
            _delConsole = del;
            _browser = b;
        }

        private void log(string str)
        {
            _delConsole.Invoke(str);
        }

        public void apply(string msid, string gamertag)
        {
            string url = "https://live.xbox.com/fr-FR/Activity?compareTo=" + gamertag.Replace(" ", "%20");
            string html = _browser.getWebPageActivity(url, gamertag);

            //extract games
            string pattern = "<LI class=\"game.*?</LI>";
            MatchCollection matchCol = Regex.Matches(html, pattern, RegexOptions.Singleline);

            //for each game
            for (int i = 0; i < matchCol.Count; ++i)
            {
                Match m = matchCol[i];

                //extract game info
                //1=>msid
                //2=>box
                //3=>name
                //4=>achievements unlocked count
                //5=>achievements count
                pattern = "<LI class=\"game ([0-9]*)?\".*?src=\"(.*)?\"></A>.*?<A class=gameTitle.*?>(.*)?</A></H3>.*?<DIV class=achievement><SPAN>([0-9]*)</SPAN>/<SPAN>([0-9]*)</SPAN>";
                Match acheMatch = Regex.Match(m.Groups[0].Value, pattern, RegexOptions.Singleline);

                //check if the msid is ok
                if (acheMatch.Groups[1].Value != msid)
                    continue;

                string gameMSID = acheMatch.Groups[1].Value;
                string gameBoxSrc = acheMatch.Groups[2].Value;
                string gameName = acheMatch.Groups[3].Value;
                int gameAchievementsCount = int.Parse(acheMatch.Groups[5].Value);

                //add the game 
                int iGameId = DBInterface.getGameExists(msid);
                if (iGameId == -1)
                {
                    log("--New Game");

                    //create the game in database
                    iGameId = DBInterface.getNextValidIdForGame();
                    DBInterface.addNewGame(iGameId, gameName, gameBoxSrc, gameMSID, gameAchievementsCount);
                }

                //add the achievements
                //extract achievements data
                JSONData achievements = scanAchievements(msid, gamertag);

                //create directory
                DBInterface.ftpCreateDirectory(Constant.FTP_ACHE_IMG + "/" + iGameId.ToString());

                //for each achievements
                foreach (JSONAchievement ache in achievements._achievements)
                {
                    bool acheExists = DBInterface.getAchievementExists(iGameId, ache.Id);
                    if (acheExists)
                        continue;

                    int acheID = DBInterface.getNextValidIdForAchievement();
                    //add achievement to the game
                    if (ache.IsHidden)
                    {
                        DBInterface.addAchievementToGame(acheID, "Succès secret", "Ce succès est secret. Vous devez le déverrouiller pour en savoir plus.", main.UrlHiddenAchievement, ache.Id, iGameId);
                        log("---New achievement : Succès secret");
                    }
                    else
                    {
                        DBInterface.addAchievementToGame(acheID, ache.Name, ache.Description, ache.TileUrl, ache.Id, iGameId);
                        log("---New achievement : " + ache.Name);
                    }

                }
                return;
            }
        }

        private JSONData scanAchievements(string gameMSID, string gamertag)
        {
            //get the achievements page
            _browser.getWebPageAchievement("about:blank");
            string url = "https://live.xbox.com/fr-FR/Activity/Details?titleId=" + gameMSID + "&compareTo=" + gamertag.Replace(" ", "%20");
            string html = _browser.getWebPageAchievement(url);

            //extract the json in resultRegex.Groups[1].Value
            string pattern = @"broker\.publish\(routes\.activity\.details\.load, (.*)?\);";
            Match resultRegex = Regex.Match(html, pattern);
            while (resultRegex.Groups.Count < 2)
            {
                html = _browser.getWebPageAchievement(url);
                resultRegex = Regex.Match(html, pattern);
            }

            JSONData ret = Extract.extractAchievements(html);
            return ret;
        }
    }
}
